<template>
    <div class="account-settings-page">
        <van-nav-bar title="Account Settings" left-text="Back" left-arrow @click-left="$router.back()" />

        <div class="settings-content">
            <van-cell-group inset title="Account Information">
                <van-cell title="Change Password" is-link @click="changePassword" />
                <van-cell title="Update Email" is-link @click="updateEmail" />
                <van-cell title="Two-Factor Authentication" is-link>
                    <template #right-icon>
                        <van-switch v-model="settings.twoFactor" />
                    </template>
                </van-cell>
            </van-cell-group>

            <van-cell-group inset title="Data Management">
                <van-cell title="Download My Data" is-link @click="downloadData" />
                <van-cell title="Export Training History" is-link @click="exportHistory" />
            </van-cell-group>

            <van-cell-group inset title="Danger Zone">
                <van-cell title="Deactivate Account" is-link @click="deactivateAccount" />
                <van-cell title="Delete Account" is-link @click="deleteAccount" />
            </van-cell-group>
        </div>

        <!-- Password Change Dialog -->
        <van-dialog v-model:show="showPasswordDialog" title="Change Password" show-cancel-button
            @confirm="confirmPasswordChange">
            <van-form>
                <van-field v-model="passwordForm.currentPassword" type="password" placeholder="Current Password"
                    required />
                <van-field v-model="passwordForm.newPassword" type="password" placeholder="New Password" required />
                <van-field v-model="passwordForm.confirmPassword" type="password" placeholder="Confirm New Password"
                    required />
            </van-form>
        </van-dialog>

        <!-- Email Update Dialog -->
        <van-dialog v-model:show="showEmailDialog" title="Update Email" show-cancel-button
            @confirm="confirmEmailUpdate">
            <van-field v-model="newEmail" type="email" placeholder="New Email Address" required />
        </van-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { showToast, showConfirmDialog } from 'vant'
import { userApi } from '@/api/user'

const settings = reactive({
    twoFactor: false
})

const showPasswordDialog = ref(false)
const showEmailDialog = ref(false)
const passwordForm = reactive({
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
})
const newEmail = ref('')

const changePassword = () => {
    showPasswordDialog.value = true
}

const updateEmail = () => {
    showEmailDialog.value = true
}

const confirmPasswordChange = async () => {
    if (!passwordForm.currentPassword || !passwordForm.newPassword || !passwordForm.confirmPassword) {
        showToast('Please fill in all fields')
        return
    }

    if (passwordForm.newPassword !== passwordForm.confirmPassword) {
        showToast('New passwords do not match')
        return
    }

    if (passwordForm.newPassword.length < 8) {
        showToast('Password must be at least 8 characters')
        return
    }

    try {
        const response = await userApi.changePassword({
            current_password: passwordForm.currentPassword,
            password: passwordForm.newPassword,
            password_confirmation: passwordForm.confirmPassword
        })

        if (response.success) {
            showToast('Password updated successfully!')
            showPasswordDialog.value = false
            // Reset form
            Object.assign(passwordForm, {
                currentPassword: '',
                newPassword: '',
                confirmPassword: ''
            })
        } else {
            throw new Error(response.error || 'Password change failed')
        }
    } catch (error) {
        console.error('Password change error:', error)
        showToast('Failed to update password')
    }
}

const confirmEmailUpdate = async () => {
    if (!newEmail.value) {
        showToast('Please enter a new email address')
        return
    }

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!emailRegex.test(newEmail.value)) {
        showToast('Please enter a valid email address')
        return
    }

    try {
        // Simulate API call
        await new Promise(resolve => setTimeout(resolve, 1000))
        showToast('Verification email sent to new address!')
        showEmailDialog.value = false
        newEmail.value = ''
    } catch (error) {
        showToast('Failed to update email')
    }
}

const downloadData = () => {
    showToast('Data download started!')
}

const exportHistory = () => {
    showToast('Training history export started!')
}

const deactivateAccount = async () => {
    const result = await showConfirmDialog({
        title: 'Deactivate Account',
        message: 'Are you sure you want to deactivate your account?'
    })
    if (result) {
        showToast('Account deactivated')
    }
}

const deleteAccount = async () => {
    const result = await showConfirmDialog({
        title: 'Delete Account',
        message: 'This action cannot be undone. Are you sure?',
        confirmButtonColor: '#ee0a24'
    })
    if (result) {
        showToast('Account deletion initiated')
    }
}
</script>

<style lang="scss" scoped>
.account-settings-page {
    min-height: 100vh;
    background: #f8f9fa;
}

.settings-content {
    padding: 16px;
}
</style>